package com.oa.common.utils;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;

@Component
public class FileUtil {

    private static String realPath;

    public static String ImageUpload(MultipartFile file, HttpServletRequest request) throws IllegalStateException, IOException {
        String savePaths = "";
        if (file != null) {// 判断上传的文件是否为空
            // String path="";// 文件路径
            String type = null;// 文件类型
            String fileName = file.getOriginalFilename();// 文件原名称
            // 判断文件类型
            if (fileName.isEmpty()) {
                return "没有图片请重新选择";
            }
            type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())  || "TIF".equals(type.toUpperCase()) || "JPEG".equals(type.toUpperCase())) {
                // 自定义的文件名称
                String trueFileName = fileName; //15312196403485.jpg
                String realUrl = realPath + "image/examination-approval-project/" +AppUtils.getUUID();
                File d = new File(realUrl);
                d.mkdirs();
                String path = realUrl + "/" + trueFileName;
                // 转存文件到指定的路径
                file.transferTo(new File(path));
                savePaths = path;
            } else {
                // 自定义的文件名称
                String trueFileName = fileName;
                String realUrl = realPath + "file/examination-approval-project/" + AppUtils.getUUID();
                File d = new File(realUrl);
                d.mkdirs();
                String path = realUrl + "/" + trueFileName;
                // 转存文件到指定的路径
                file.transferTo(new File(path));
                savePaths = path;
            }
        } else {
            return "文件类型为空";
        }
        return savePaths;
    }

    public static String getRealPath() {
        return realPath;
    }

    @Value("${url.saveUrl}")
    public void setRealPath(String realPath) {
        FileUtil.realPath = realPath;
    }

    public static String getFilePath() {
        return realPath;
    }

    /***
     * 删除指定文件夹下所有文件
     *
     * @param path 文件夹完整绝对路径
     * @return
     */
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);// 再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    /***
     * 删除文件夹
     *
     * @param folderPath 文件夹完整绝对路径
     */
    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); // 删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            java.io.File myFilePath = new java.io.File(filePath);
            myFilePath.delete(); // 删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String ImageUpload2(MultipartFile file) throws IllegalStateException, IOException {
        String savePaths = "";
        if (file != null) {// 判断上传的文件是否为空
            // String path="";// 文件路径
            String type = null;// 文件类型
            String fileName = file.getOriginalFilename();// 文件原名称
            // 判断文件类型
            if (fileName.isEmpty()) {
                return "没有图片请重新选择";
            }
            type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())  || "JPEG".equals(type.toUpperCase())) {
                // 自定义的文件名称
                String trueFileName = fileName; //15312196403485.jpg
                String realUrl = realPath + "image/" +AppUtils.getUUID();
                File d = new File(realUrl);
                d.mkdirs();
                String path = realUrl + "/" + trueFileName;
                // 转存文件到指定的路径
                file.transferTo(new File(path));
                savePaths = path;
            } else {
                // 自定义的文件名称
                String trueFileName = fileName;
                String realUrl = realPath + "file/" + AppUtils.getUUID();
                File d = new File(realUrl);
                d.mkdirs();
                String path = realUrl + "/" + trueFileName;
                // 转存文件到指定的路径
                file.transferTo(new File(path));
                savePaths = path;
            }
        } else {
            return "文件类型为空";
        }
        return savePaths;
    }

    /**
     * 复制文件
     *
     * @param srcPath
     *            源文件绝对路径
     * @param destDir
     *            目标文件所在目录
     * @return boolean
     */
    public static boolean copyFile(String srcPath, String destDir) {
        boolean flag = false;

        File srcFile = new File(srcPath);
        // 源文件不存在
        if (!srcFile.exists()) {
            System.out.println("源文件不存在");
            return false;
        }
        // 获取待复制文件的文件名
        String fileName = srcPath
                .substring(srcPath.lastIndexOf("/"));
        String destPath = destDir + fileName;
        if (destPath.equals(srcPath)) {
            // 源文件路径和目标文件路径重复
            System.out.println("源文件路径和目标文件路径重复!");
            return false;
        }
        File destFile = new File(destPath);
        if (destFile.exists() && destFile.isFile()) {
            // 该路径下已经有一个同名文件
            System.out.println("目标目录下已有同名文件!");
            return false;
        }

        File destFileDir = new File(destDir);
        destFileDir.mkdirs();
        try {
            FileInputStream fis = new FileInputStream(srcPath);
            FileOutputStream fos = new FileOutputStream(destFile);
            byte[] buf = new byte[1024];
            int c;
            while ((c = fis.read(buf)) != -1) {
                fos.write(buf, 0, c);
            }
            fis.close();
            fos.close();

            flag = true;
        } catch (IOException e) {
            //
        }

        if (flag) {
            System.out.println("复制文件成功!");
        }

        return flag;
    }

    /**
     * 根据url下载并保存到指定位置
     * @param urlString
     * @param filename
     * @param savePath
     * @throws Exception
     */
    public static void downloadByUrl(String urlString, String filename,String savePath) throws Exception {
        // 构造URL
        URL url = new URL(urlString);
        // 打开连接
        URLConnection con = url.openConnection();
        //设置请求超时为5s
        con.setConnectTimeout(5*1000);
        // 输入流
        InputStream is = null;
        try{
           is = con.getInputStream();
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            File sf=new File(savePath);
            if(!sf.exists()){
                sf.mkdirs();
            }
            // 新的图片文件名 = 编号 +"."图片扩展名
            OutputStream os = new FileOutputStream(sf.getPath()+"\\"+filename);
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            // 完毕，关闭所有链接
            os.close();
        }catch (FileNotFoundException e){
            e.getMessage();
        }finally {
            is.close();
        }
    }

    public static void deleteFile(String url){
        if(url.length() < 20){
            return;
        }
//        String imgPath = url.replaceAll("https://www.qhspj.com//examination-approval-project", "/home/image/examination-approval-project");
        String imgPath = url.replaceAll("https://www.qhspj.com//examination-approval-project", "/home/image/examination-approval-project");
        String ipath = imgPath.substring(0, imgPath.lastIndexOf('/'));
        cn.hutool.core.io.FileUtil.del(ipath);
        String filePath = url.replaceAll("https://www.qhspj.com//examination-approval-project", "/home/file/examination-approval-project").replaceAll("jpg", "ofd");
        String fpath = filePath.substring(0, filePath.lastIndexOf('/'));
        cn.hutool.core.io.FileUtil.del(fpath);
    }

}
